package com.momomian.common.annotation.impl;


import com.momomian.common.annotation.DigitsMustIn;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;

/**
 * @author momomian
 * @version 1.0
 * @date 2020/10/22
 * @description  多选字段校验实现
 **/

public class DigitsMustInValidator implements ConstraintValidator<DigitsMustIn, String> {


    private String fileld;
    /**
     * 配置为true，校验 要求传值必须只有其中一个
     */
    private boolean single;


    @Override
    public void initialize(DigitsMustIn constraintAnnotation) {
        this.single = constraintAnnotation.single();
        this.fileld = constraintAnnotation.inArray();
    }


    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isEmpty(value)) {
            return true;
        }
        String[] strings = fileld.split(",");
        List<String> list = Arrays.asList(strings);
        String[] values = value.split(",");
        List<String> valueList = Arrays.asList(values);
        if(single && valueList.size() != 1){
            constraintValidatorContext.disableDefaultConstraintViolation();
            constraintValidatorContext.buildConstraintViolationWithTemplate("[" + value + "]" + "必须为" + Arrays.toString(strings) + "其中之一").addConstraintViolation();
            return false;
        }
        if (list.containsAll(valueList)) {
            return true;
        }
        //禁用默认的message的值
        constraintValidatorContext.disableDefaultConstraintViolation();
        //重新添加错误提示语句
        constraintValidatorContext.buildConstraintViolationWithTemplate("[" + value + "]" + "必须在" + Arrays.toString(strings) + "之内").addConstraintViolation();
        return false;
    }
}